const express = require('express')
const router = express.Router()
const { SuccessModel, ErrorModel } = require('../model/resModel')
const { login } = require('../controller/user')

router.post('/login', (req, res, next) => {
  const { username, password } = req.body
  const result = login(username, password)

  return result.then(data => {
    if (data.username) {
      req.session.username = data.username
      req.session.realname = data.realname
      
      res.json(new SuccessModel('登录成功'))
      return
    }
    res.json(new SuccessModel('未登录'))
  })
})

router.get('/login-test', (req, res, next) => {
  if (req.session.username) {
    res.json(new SuccessModel('已登录'))
    return
  }
  res.json(new ErrorModel('未登录'))
})

router.get('/session', (req, res, next) => {
  // console.log(res)
  // console.log(req.session)
  res.json({
    code: 0,
    msg: '测试session'
  })
})

router.get('/session-test', (req, res, next) => {
  console.log(req.session)
  const session = req.session
  if (session.viewNum == null) {
    session.viewNum = 0
  }
  session.viewNum ++
  res.json({
    session: session.viewNum
  })
})

module.exports = router
